package com.rocksea.app.service;

import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;

public class DownloadService extends Service
{
    private BroadcastReceiver mBroadcastReceiver;
    private long mDownloadId;

    public DownloadService()
    {
        super();
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        mBroadcastReceiver = new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context context, Intent intent)
            {
                if (intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) != mDownloadId)
                    return;

                if (!intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
                    return;

                Uri downloadFileUri = ((DownloadManager)getSystemService(DOWNLOAD_SERVICE)).getUriForDownloadedFile(mDownloadId);
                Intent intentInstall = new Intent(Intent.ACTION_VIEW);
                intentInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intentInstall.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
                startActivity(intentInstall);
                stopSelf();
            }
        };
        registerReceiver(mBroadcastReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        Uri downloadPath = intent.getData();
        String filename = downloadPath.toString();
        filename = filename.substring(filename.lastIndexOf("/") + 1);

        Request request = new Request(downloadPath);
        request.setMimeType("application/vnd.android.package-archive");
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
        request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
        request.setTitle("下载");
        request.setDescription("正在下载");

        mDownloadId = ((DownloadManager)getSystemService(DOWNLOAD_SERVICE)).enqueue(request);

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy()
    {
        unregisterReceiver(mBroadcastReceiver);
        super.onDestroy();
    }
}
